import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import anchor from 'markdown-it-anchor'
import tocdoneright from 'markdown-it-toc-done-right'

export default function markdown(markdownFile: string) {
  let technology: string = ''

  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str: string, lang: string) {
      // 当前时间加随机数生成唯一的id标识
      const codeIndex =
        parseInt(`${Date.now()}`) + Math.floor(Math.random() * 10000000)
      // 复制功能主要使用的是 clipboard.js
      let html = `<button class="copy-btn" type="button" data-clipboard-action="copy" data-clipboard-target="#copy${codeIndex}">复制</button>`
      const linesLength = str.split(/\n/).length + 40

      // 生成行号
      let linesNum = '<span aria-hidden="true" class="line-numbers-rows">'
      for (let index = 0; index < linesLength; index++) {
        linesNum = linesNum + '<span></span>'
      }
      linesNum += '</span>'
      if (lang && hljs.getLanguage(lang)) {
        try {
          // highlight.js 高亮代码
          const preCode = hljs.highlight(lang, str, true).value
          html = html + preCode
          if (linesLength) {
            html += '<b class="name">' + lang + '</b>'
          }
          // 将代码包裹在 textarea 中
          return `<pre class="hljs"><code>${html}</code>${linesNum}</pre><textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy${codeIndex}">${str.replace(
            /<\/textarea>/g,
            '&lt;/textarea>'
          )}</textarea>`
        } catch (error) {
          console.log(error)
        }
      }

      const preCode = md.utils.escapeHtml(str)
      html = html + preCode
      // 将代码包裹在 textarea 中
      return `<pre class="hljs"><code>${html}</code>${linesNum}</pre><textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy${codeIndex}">${str.replace(
        /<\/textarea>/g,
        '&lt;/textarea>'
      )}</textarea>`
    },
  })
    .use(anchor, {
      permalink: true,
      permalinkBefore: true,
      permalinkSymbol: '🍍',
    })
    .use(tocdoneright)
  technology = md.render(markdownFile + ' ${toc}')

  return technology
}
